/*
 * RegionBoard.h
 *
 *  Created on: Jun 3, 2011
 *      Author: hongyang
 */

#include "Board.h"
#include "Region.h"
#include "Block.h"
#include "../smartgame/SgPointSet.h"
#include "../smartgame/SgPoint.h"
#include "../smartgame/SgBlackWhite.h"
#include "../smartgame/SgBWArray.h"
#include "../smartgame/SgVector.h"

#ifndef REGIONBOARD_H_
#define REGIONBOARD_H_

/**
 * maintains the set of regions on board.
 * provides an evaluation function based on tactical reading.
 */
class RegionBoard {
public:
	RegionBoard(Board& board);
	~RegionBoard();

	void copy(const RegionBoard& r);
	void clear();

	bool simpleCanMerge(SgPointSet& s1, SgPointSet& s2, SgBlackWhite color) const;

	Region* genRegion(SgBlackWhite moveColor);

	Region* prevRegionAt(SgPoint p1, SgPoint p2, SgBlackWhite color) const;
	void regionsAt(const SgPointSet& p, SgBlackWhite color, SgVectorOf<Region>& regions) const;
	Region* mergeRegion(Region* r1, Region* r2);

	const Board& getBoard() const {
		return board;
	}

	void onExecMove(Move move);
	void updateRegion(Move move);
	const SgVectorOf<Region>& getAllRegions(SgBlackWhite color) const;
	void print() const;
	void print(const SgVectorOf<Region> regions) const;
	void endOfGame(SgBlackWhite player) const;
	SgBlackWhite whoWins() const;

	bool isWrapped(Region& r) const;
	bool isDead(Region& r) const;
	void removeBlocks(SgArrayList<Block*, 4> blocks);

private:

	Board& board;

	SgBWArray<SgPointArray<Region*> > regions;

	SgBWArray<SgVectorOf<Region> > allRegions;

	void expandRegion(Region* r);
	void addRegion(Region* r);
	void removeRegion(Region* r);
	void setRegionArrays(Region* r);
};


inline const SgVectorOf<Region>& RegionBoard::getAllRegions(SgBlackWhite color) const {
	return allRegions[color];
}

inline Region* RegionBoard::prevRegionAt(SgPoint p1, SgPoint p2, SgBlackWhite c) const {
	Region* r = regions[c][p1];
	if(r == 0) {
		r = regions[c][p2];
	}
	SG_ASSERT(r != 0);
	//SgDebug() << "prev " << regions[c][p1] << " " << regions[c][p2] << "\n";
	return r;
}


#endif /* REGIONBOARD_H_ */
